# encoding: utf-8
# @File  : mysql.py
# @Author: shaoyun
# @Date  :  2025/05/11
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker

from app.core.config import settings

# 创建同步SQLAlchemy引擎
engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, pool_pre_ping=True)

# 创建同步会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建异步引擎（注意需要修改数据库URI）
async_engine = create_async_engine(
    settings.SQLALCHEMY_DATABASE_URI.replace('mysql+pymysql://', 'mysql+aiomysql://'),
    pool_pre_ping=True
)

# 创建异步会话工厂
AsyncSessionLocal = async_sessionmaker(
    async_engine,
    class_=AsyncSession,
    expire_on_commit=False
)

# 声明基类
Base = declarative_base()


def get_db():
    """获取数据库会话的依赖项"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


async def get_async_db():
    """获取异步数据库会话的依赖项"""
    async with AsyncSessionLocal() as session:
        yield session